package com.service.hibernate.dao;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

import com.service.hibernate.pojos.Services;
import com.service.hibernate.pojos.Stocks;
import com.service.hibernate.pojos.ServicesUses.ServicesUses;
import com.service.hibernate.util.HibernateUtil;

public class ServicesDAO extends GenericDAO<Services> {

	@Override
	public void addData(Services dataObject) {
		try {
			System.out
					.println("----------------------------------------------------------------------------------------------------");
			System.out
					.println("In ServicescDAO overridden - addData() Method :");
			System.out
					.println("----------------------------------------------------------------------------------------------------");

			// Testing Purpose
			Stocks stk1 = (Stocks) session.get(Stocks.class, 1);

			ServicesUses sUses = new ServicesUses();
			sUses.setService(dataObject);
			sUses.setStock(stk1);
			sUses.setQuantity(5);

			dataObject.getServicesUses().add(sUses);

			session.save(dataObject);
		} catch (Exception e) {
			transaction.rollback();
			System.out
					.println("----------------------------------------------------------------------------------------------------");
			System.out.println("Error in ServicesDAO - addData() Method :");
			e.printStackTrace();
			System.out
					.println("----------------------------------------------------------------------------------------------------");
		}
		super.addData(dataObject);
	}

	public List<Stocks> getStockDetial(String vehicleNo) {
		/*
		 * Criteria criteria = session.createCriteria(StockDailyRecord.class)
		 * .add(Restrictions.le(Session ssion = factory.openSession(); "volume",
		 * 10000));
		 */
		Session ssion = HibernateUtil.getSessionFactory().openSession();
		try {
			//get data from table relevant to serviceId
			Criteria criteria = ssion.createCriteria(Services.class).add(Restrictions.eq("serviceId",Integer.parseInt(vehicleNo)));
			List<Services> listOfServices = criteria.list();
			//put relevant item details to listOfStocks list
			if (listOfServices.size()>0) {
				List<ServicesUses> listOfServiceUser = listOfServices.get(0)
						.getServicesUses();
				List<Stocks> listOfStocks = new ArrayList<Stocks>();
				if (listOfServiceUser != null) {
					for (int i = 0; i < listOfServiceUser.size(); i++) {
						listOfServiceUser.get(i).getStock().setQuantity(listOfServiceUser.get(i).getQuantity());
						listOfStocks.add(listOfServiceUser.get(i).getStock());
					}

				} else {
					System.out.println("no Items for the service");
				}
				return listOfStocks;
			}else{
				System.out.println("no serviceUser for the service");
			}
		} catch (Exception e) {
			System.out.println("Exception in com.service.hibernate.dao:" + e);
		}
		return null;
	}

}
